package com.huabo.push;

import com.huabo.utils.FastJsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 推送消息发布端
 * Created by Jackie Liu on 2017/9/1.
 */
public class PushPublisher implements InitializingBean {

    private StringRedisTemplate redisTemplate;
    private String topic;

    public void publish(PushMessage pushMessage) {
        redisTemplate.convertAndSend(topic, FastJsonUtils.objToJson(pushMessage));
    }

    public void publish(String[] deviceIds, String category, String message) {
        if (deviceIds == null || deviceIds.length == 0 || message == null) {
            return;
        }
        PushMessage pushMessage = new PushMessage();
        pushMessage.setDeviceIds(deviceIds);
        pushMessage.setMessage(message);
        pushMessage.setCategory(category);
        publish(pushMessage);
    }

    public void publish(String deviceId, String category, String message) {
        if (StringUtils.isEmpty(deviceId) || message == null) {
            return;
        }
        publish(new String[]{deviceId}, category, message);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    i++;
                    PushPublisher pushPublisher = SpringContextHelper.getBean(PushPublisher.class);
                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setDeviceIds(new String[]{"1", "2", "3"});
                    pushMessage.setMessage("消息内容：" + i);
                    pushPublisher.publish(pushMessage);
                }
            }
        }).start();*/
    }

    public StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }
}
